package com.hc.digest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 消息摘要算法，为了防止篡改
 * 常见的加密算法：md5，sha1，sha256，sha512
 *
 * @author : Henry
 * {@code CreateTime}: 2025-08-27 09:33
 * {@code Version}: 1.0
 */
public class DigestDemo {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 原文
        String input = "aa";
        // 算法
        String algorithm = "MD5";
        String md5 = getDigest(algorithm, input);
        System.out.println("md5: " + md5);

        String sha1 = getDigest("SHA-1", input);
        System.out.println("sha1: " + sha1);

        String sha256 = getDigest("SHA-256", input);
        System.out.println("sha256: " + sha256);

        String sha512 = getDigest("SHA-512", input);
        System.out.println("sha512: " + sha512);
    }

    private static String getDigest(String algorithm, String input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] digest1 = digest.digest(input.getBytes());
        String hex = toHex(digest1);
        return hex;
    }

    private static String toHex(byte[] digest) {
        StringBuilder stringBuilder = new StringBuilder();
        // 对密文进行迭代
        for (byte b : digest) {
            // 把密文转换成16进制
            String hexString = Integer.toHexString(b & 0xff);
//            System.out.println(hexString);
            // 如果密文的长度是1，需要在高位补0
            if (hexString.length() == 1) {
                stringBuilder.append("0");
            }
            stringBuilder.append(hexString);
        }
//        System.out.println(stringBuilder);
//        System.out.println(new String(Base64.getEncoder().encode(digest1)));
        return stringBuilder.toString();
    }
}
